class User {
  constructor(id, username, email, balance) {
    this.id = id;                     // 用户ID
    this.username = username;         // 用户名
    this.email = email;               // 邮箱
    this.balance = balance;           // 账户余额
    this.portfolio = {};              // 投资组合 {symbol: {quantity, averagePrice}}
    this.tradeHistory = [];           // 交易历史
  }

  // 买入股票
  buyStock(symbol, quantity, price) {
    const totalCost = quantity * price;
    
    if (this.balance < totalCost) {
      throw new Error('Insufficient balance');
    }
    
    // 扣除资金
    this.balance -= totalCost;
    
    // 更新投资组合
    if (this.portfolio[symbol]) {
      // 计算新的平均价格
      const existingQuantity = this.portfolio[symbol].quantity;
      const existingAveragePrice = this.portfolio[symbol].averagePrice;
      
      const newQuantity = existingQuantity + quantity;
      const newAveragePrice = (
        (existingQuantity * existingAveragePrice) + (quantity * price)
      ) / newQuantity;
      
      this.portfolio[symbol] = {
        quantity: newQuantity,
        averagePrice: newAveragePrice
      };
    } else {
      this.portfolio[symbol] = {
        quantity: quantity,
        averagePrice: price
      };
    }
    
    return true;
  }

  // 卖出股票
  sellStock(symbol, quantity, price) {
    if (!this.portfolio[symbol] || this.portfolio[symbol].quantity < quantity) {
      throw new Error('Insufficient stock quantity');
    }
    
    // 增加资金
    const totalRevenue = quantity * price;
    this.balance += totalRevenue;
    
    // 更新投资组合
    this.portfolio[symbol].quantity -= quantity;
    
    // 如果数量为0，移除该股票
    if (this.portfolio[symbol].quantity === 0) {
      delete this.portfolio[symbol];
    }
    
    return true;
  }

  // 获取投资组合
  getPortfolio() {
    return this.portfolio;
  }

  // 获取账户信息
  getAccountInfo() {
    return {
      id: this.id,
      username: this.username,
      email: this.email,
      balance: this.balance,
      portfolio: this.portfolio
    };
  }

  // 添加交易到历史记录
  addTradeToHistory(trade) {
    this.tradeHistory.push(trade);
  }

  // 获取交易历史
  getTradeHistory() {
    return this.tradeHistory;
  }
}

module.exports = User;